#include "color.widget.h"

#include <QtWidgets/QtWidgets>

struct ColorWidgetPriv {
	QString title;
	QColor color;
	ColorWidgetPriv(const QString& t, const QColor& c): title{t}, color{c} { }
};

ColorWidget::ColorWidget(const QString& t, const QString& desc, QWidget* par):
	QWidget{par}, priv{new ColorWidgetPriv{t, QColor{0, 0, 0}}}
{
	setToolTip(desc);
}
ColorWidget::~ColorWidget() {
	delete priv;
}

void ColorWidget::setColor(const QColor& c) {
	if(c!=priv->color) {
		priv->color=c;
		update();
		Q_EMIT colorChanged(priv->color);
	}
}
const QColor& ColorWidget::color() const {
	return priv->color;
}

void ColorWidget::mouseReleaseEvent(QMouseEvent* event) {
	if(event->button()==Qt::LeftButton && underMouse()) {
		auto c=QColorDialog::getColor(priv->color, this, priv->title, 0);
		if(c.isValid()) {
			setColor(c);
		}
	}
}

#define PADDING 2
void ColorWidget::paintEvent(QPaintEvent* event) {
	QPainter p{this};
	p.setRenderHint(QPainter::Antialiasing, true);
	int w=width()-2*PADDING;
	int h=height()-2*PADDING;
	p.fillRect(PADDING, PADDING, w, h, priv->color);
}

QSize ColorWidget::minimumSizeHint() const {
	return {48, 16};
}
QSize ColorWidget::sizeHint() const {
	return {64, 16};
}
